package com.itheima.web.servlet;

import com.itheima.domain.User;
import com.itheima.service.Service;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1.设置请求编码
            request.setCharacterEncoding("utf-8");
            //2获取用户输入的验证码
            String verifycode = request.getParameter("verifycode");
            //3.获取session中的验证码
            HttpSession session = request.getSession();
            String checkcode_server =(String) session.getAttribute("CHECKCODE_SERVER");
            //4.确保验证码的一次性
            session.removeAttribute("CHECKCODE_SERVER");

            //5.判断两个验证码是否相同
            if (!verifycode.equalsIgnoreCase(checkcode_server)){
                //验证码不相同
                //使用请求转发存储错误信息
                request.setAttribute("msg","验证码错误");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
                return;
            }
            //验证相同，判断用户名或密码是否相同
            //获取所有请求参数
            Map<String, String[]> parameterMap = request.getParameterMap();
            //封装到User对象中
            User user = new User();
            BeanUtils.populate(user,parameterMap);
            //调用Service查询
            Service service = new Service();
            User user1 = service.login(user);

            //判断user1是否为空
            if(user1==null){
                //用户名或密码错误，请求转发存入错误信息
                request.setAttribute("msg",user1);
                request.getRequestDispatcher("/login.jsp").forward(request,response);
            }
            //用户名和密码正确
            //将信息保存到session域中
            session.setAttribute("user",user1);

            //记住用户名

            String rememberMe = request.getParameter("rememberMe");
            if("yes".equals(rememberMe)){
                //使用cookie保存用户名
                Cookie cookie = new Cookie("rememberMe",user1.getUsername());
                cookie.setMaxAge(7*24*60*60);
                response.addCookie(cookie);

            }
            //重定向到success.jsp中
            response.sendRedirect(request.getContextPath()+"/success.jsp");


        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
